package com.jy.adscm.operation.base.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.bean.system.JyDept;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.operation.base.bean.QueryTaskManager;
import com.jy.adscm.operation.base.bean.TaskManager;
import com.jy.adscm.operation.base.bean.TaskManagerdetail;
import com.jy.adscm.operation.base.bean.TaskManagerinfo;
import com.jy.adscm.operation.base.mapper.mysql.TaskManagerMapper;
import com.jy.adscm.operation.base.mapper.mysql.TaskManagerdetailMapper;
import com.jy.adscm.operation.base.mapper.mysql.TaskManagerinfoMapper;
import com.jy.adscm.operation.base.service.TaskManagerService;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.system.mapper.mysql.JyDeptMapper;
import com.jy.adscm.system.mapper.mysql.JyUserMapper;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.utils.AdscmDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyl
 * @since 2018-12-11
 */
@Service
public class TaskManagerServiceImpl extends ServiceImpl<TaskManagerMapper, TaskManager> implements TaskManagerService {
    @Autowired
    JyUserMapper jyUserMapper;
    @Autowired
    JyDeptMapper jyDeptMapper;
    @Autowired
    TaskManagerinfoMapper taskManagerinfoMapper;
    @Autowired
    TaskManagerdetailMapper taskManagerdetailMapper;
   @Transactional
    @Override
    public Boolean updateTaskManager(TaskManager taskManager, Token token) throws AdscmSystemException {
         if (taskManager.getCreator().equals(String.valueOf(token.getUser().getId()))){

             taskManager.setIsCreatorUpdate("1");
         }
         if (taskManager.getPerformer().equals(String.valueOf(token.getUser().getId()))){
             taskManager.setIsPerformerUpdate("1");
         }
        TaskManager oldTaskManager = super.selectById(taskManager.getId());
         //每日任务且是自己登陆的
        if (taskManager.getCreator().equals(taskManager.getPerformer()) && taskManager.getCreator().equals(token.getUser().getId().toString())
             && "1".equals(taskManager.getIsEveryDayTask())
            ){
             if(AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getEndDate(),null)){
                 if (!AdscmBaseUtils.getInstance().isNotEmpty(oldTaskManager.getEndDate(),null)){
                     taskManager.setTaskState(1);
                 }
             }
         } else {
            //如果是未接收的，且登录人不是创建人就不能做修改了
            if ("-1".equals(taskManager.getIsReceived())&&!taskManager.getCreator().equals(token.getUser().getId().toString())){
                throw  new AdscmSystemException("不是创建人不能修改");
            }
            //判断是接收
            if (!"-1".equals(taskManager.getIsReceived())){
                taskManager.setReceivedDate(new Date());
            }
            //判断是否是开始任务
            if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getStartDate(),null)){
                if (!AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getReceivedDate(),null)){
                    throw  new AdscmSystemException("任务未接收不能填写开始时间");
                  }
                if (!AdscmBaseUtils.getInstance().isNotEmpty(oldTaskManager.getStartDate(),null)){
                        taskManager.setStartCreateDate(new Date());
                }
            }

            //判断任务是否已经结束
            if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getEndDate(),null)){
                if (!AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getStartDate(),null)){
                    throw  new AdscmSystemException("没有开始时间不能填写结束始时间");
                }

                if (!AdscmBaseUtils.getInstance().isNotEmpty(oldTaskManager.getEndDate(),null)){
                    taskManager.setEndDateCreateDate(new Date());
                }

            }
            //如果复核记录不等于空
            if (!"-1".equals(taskManager.getIsReviewTask())){
                if (!AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getEndDate(),null)){
                    throw  new AdscmSystemException("任务未结束，不能进行复核");
                }
                taskManager.setReviewTime(new Date());
                if ("1".equals(taskManager.getReviewResult())){
                    taskManager.setTaskState(1);
                }
            }
        }
        boolean result = super.updateById(taskManager);
        return result;
    }

    @Override
    public List<TaskManager> selectTaskManager(Token token) throws AdscmSystemException {
        List<TaskManager> taskManagers=new ArrayList<>();
        //首先查询是否是管理员
        if (AdscmBaseUtils.getInstance().isNotEmpty(token.getUser().getId(),null)){
                Wrapper<TaskManager> wrapper =new EntityWrapper<>();
                wrapper.eq("creator",token.getUser().getId());
                wrapper.eq("task_state",0);
                wrapper.ne("performer",token.getUser().getId());
                wrapper.orderBy("task_state",true);
                wrapper.orderBy("create_date",false);
                taskManagers = super.selectList(wrapper);

        }else {
            throw new AdscmSystemException("未获取到登录消息");
        }
        for (TaskManager taskManager : taskManagers) {
              if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getCreator(),null)){
                  JyUser jyUser = jyUserMapper.selectById(taskManager.getCreator());
                  taskManager.setCreatorName(jyUser.getName());
              }
              if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getPerformer(),null)){
                  JyUser jyUser = jyUserMapper.selectById(taskManager.getPerformer());
                  taskManager.setPerformerName(jyUser.getName());
              }
            if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getDept(),null)){
                JyDept jyDept = jyDeptMapper.selectById(taskManager.getDept());
                taskManager.setDeptName(jyDept.getDeptName());
            }
        }
        return taskManagers;
    }

    @Override
    public List<JyUser> selectTaskPerformPerson(Integer deptId ) {
        Wrapper<JyUser> wrapper=new EntityWrapper<>();
        wrapper.eq("dept_id",deptId);
        wrapper.setSqlSelect("id","name");
        List<JyUser> jyUsers = jyUserMapper.selectList(wrapper);
        return jyUsers;
    }

    @Override
    public List<JyDept> selectDepts() {
        Wrapper<JyDept> wrapper=new EntityWrapper<>();
        List<JyDept> jyDepts = jyDeptMapper.selectList(wrapper);
        return jyDepts;
    }

    @Override
    public Page<TaskManager> selectMyTaskManager(Page<TaskManager> page,QueryTaskManager queryTaskManager,Integer taskState, Token token) {
        Date formateDate = AdscmDateUtils.getFormateDate(new Date());

        Date firstDay = AdscmDateUtils.getFirstDayOfTheMonth(new Date());

        Date lastDay = AdscmDateUtils.getLastDayOfTheMonth(new Date());
        boolean monthStart = AdscmDateUtils.isMonthStart(new Date());
        //是否是月初 如果是吧开始时间往后减一个月
        if (monthStart){
            firstDay= AdscmDateUtils.getThatDate(firstDay,-1,Calendar.MONTH);
        }


        Date monday = AdscmDateUtils.getMonday(new Date());
        Date sunDay = AdscmDateUtils.getSunDay(new Date()) ;
        //是否周一，如果周一往前减一周 或者周日
        boolean isMonday = AdscmDateUtils.isMonday(new Date());
        boolean isSunDay = AdscmDateUtils.getIsSunDay(new Date());
        if (isMonday||isSunDay){
            monday=AdscmDateUtils.getThatDate(monday,-7,Calendar.DATE);
        }
        Wrapper<TaskManager> wrapper =new EntityWrapper<>();
        wrapper.eq("task_state",taskState);
        wrapper.eq("performer",token.getUser().getId());
        wrapper.eq("isEveryDayTask","0");
        if (taskState==0){
            wrapper.orNew();
            wrapper.eq("performer",token.getUser().getId());
            wrapper.eq("isEveryDayTask","1");
            wrapper.eq("finish_date",formateDate);
            //查询周总结
            wrapper.orNew();
            wrapper.eq("performer",token.getUser().getId());
            wrapper.eq("creator",token.getUser().getId());
            wrapper.eq("isEveryDayTask","2");
            wrapper.ge("create_date",monday);
            wrapper.le("create_date",sunDay);
            //查询月总结
            wrapper.orNew();
            wrapper.eq("performer",token.getUser().getId());
            wrapper.eq("creator",token.getUser().getId());
            wrapper.eq("isEveryDayTask","3");
            wrapper.ge("create_date",firstDay);
            wrapper.le("create_date",lastDay);
            wrapper.orderBy("create_date",false);
            page = super.selectPage(page,wrapper);
            page.setTotal(super.selectCount(wrapper));
        }
        if (taskState==1){
            wrapper.orNew();
            wrapper.eq("performer",token.getUser().getId());
            wrapper.eq("isEveryDayTask","1");
            wrapper.lt("finish_date",formateDate);
            wrapper.orNew();
            wrapper.eq("creator",token.getUser().getId());
            wrapper.eq("isEveryDayTask","1");
            wrapper.lt("finish_date",formateDate);
            //查询周总结
            wrapper.orNew();
            wrapper.eq("performer",token.getUser().getId());
            wrapper.eq("creator",token.getUser().getId());
            wrapper.eq("isEveryDayTask","2");
            wrapper.le("create_date",monday);
            //查询月总结
            wrapper.orNew();
            wrapper.eq("performer",token.getUser().getId());
            wrapper.eq("creator",token.getUser().getId());
            wrapper.eq("isEveryDayTask","3");
            wrapper.le("create_date",firstDay);
            wrapper.orderBy("create_date",false);
            page = super.selectPage(page,wrapper);
            page.setTotal(super.selectCount(wrapper));
        }
        List<TaskManager> taskManagers = page.getRecords();
        for (TaskManager taskManager : taskManagers) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getCreator(),null)){
                JyUser jyUser = jyUserMapper.selectById(taskManager.getCreator());
                taskManager.setCreatorName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getPerformer(),null)){
                JyUser jyUser = jyUserMapper.selectById(taskManager.getPerformer());
                taskManager.setPerformerName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getDept(),null)){
                JyDept jyDept = jyDeptMapper.selectById(taskManager.getDept());
                taskManager.setDeptName(jyDept.getDeptName());
            }
        }


        return page;
    }

    @Transactional
    @Override
    public boolean insertEverDay(Token token) throws AdscmSystemException{
        Date formateDate = AdscmDateUtils.getFormateDate(new Date());

        //先查询一下
          Wrapper<TaskManager> wrapper =new EntityWrapper<>();
          wrapper.eq("performer",token.getUser().getId());
            wrapper.eq("creator",token.getUser().getId());
         wrapper.eq("finish_date",formateDate);
         wrapper.eq("isEveryDayTask","1");
        List<TaskManager> taskManagers = super.selectList(wrapper);
        if (taskManagers.size()>0){
            throw new AdscmSystemException("今日已经创建了每日任务");
        }
        TaskManager taskManager =new TaskManager();
        taskManager.setTaskName("每日任务");
        taskManager.setCreateDate(new Date());
        taskManager.setCreator(token.getUser().getId().toString());
        taskManager.setIsReceived("-1");
        taskManager.setTaskResult("-1");
        taskManager.setPerformer(token.getUser().getId().toString());
        taskManager.setDept(token.getUser().getDeptId().toString());
        taskManager.setFinishDate(formateDate);
        taskManager.setStartDate(new Date());
        taskManager.setStartCreateDate(new Date());
        taskManager.setTaskSelfEvaluation("-1");
        taskManager.setIsReviewTask("-1");
        taskManager.setTaskState(1);
        taskManager.setIsEveryDayTask("1");
        boolean insert = super.insert(taskManager);
        return insert;
    }
    @Transactional
    @Override
    public boolean inserttaskManager(TaskManager taskManager) throws AdscmSystemException {
        boolean insert = super.insert(taskManager);
        if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getTaskContent(),null)){
            TaskManagerinfo taskManagerinfo =new TaskManagerinfo();
            taskManagerinfo.setType("1");
            taskManagerinfo.setContent(taskManager.getTaskContent());
            taskManagerinfo.setPerson(taskManager.getCreator());
            taskManagerinfo.setTime(new Date());
            taskManagerinfo.setTid(taskManager.getId().toString());
           taskManagerinfoMapper.insert(taskManagerinfo);
        }
        return insert;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteTaskManager(Integer id, Token token) throws AdscmSystemException {
        TaskManager taskManager = super.selectById(id);
        if (!"0".equals(taskManager.getIsEveryDayTask())){
            throw new AdscmSystemException("不能删除该任务");
        }
        if (taskManager.getTaskState()==1){
            throw new AdscmSystemException("任务已经结束");
        }
        if (!taskManager.getCreator().equals(token.getUser().getId().toString())){
            throw new AdscmSystemException("您不能删除该任务");
        }
        //找到下面的明细删除
        Wrapper<TaskManagerdetail> wrapper =new EntityWrapper<>();
        wrapper.eq("task_id",id);
        List<TaskManagerdetail> taskManagerdetails = taskManagerdetailMapper.selectList(wrapper);
        for (TaskManagerdetail taskManagerdetail : taskManagerdetails) {
            taskManagerdetailMapper.deleteById(taskManagerdetail.getId());
        }
        boolean b = super.deleteById(id);
        return b;

    }

    @Override
    public Page<TaskManager> selectAllTaskManager(QueryTaskManager queryTaskManager, Token token) {
        Integer userId = token.getUser().getId();
        Boolean aBoolean = jyUserMapper.queryUserIsHasRole(userId.toString(), "222");

        Wrapper<TaskManager>wrapper =new EntityWrapper<>();
             if (aBoolean){
                 wrapper.eq("dept",token.getUser().getDeptId());
             }
          if (AdscmBaseUtils.getInstance().isNotEmpty(queryTaskManager.getTaskName(),null)){
              wrapper.like("task_name",queryTaskManager.getTaskName());
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(queryTaskManager.getCreator(),null)){
              wrapper.eq("creator",queryTaskManager.getCreator());
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(queryTaskManager.getPerformer(),null)){
              wrapper.eq("performer",queryTaskManager.getPerformer());
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(queryTaskManager.getStartfinishDate(),null)){
              wrapper.ge("finish_date",queryTaskManager.getStartfinishDate());
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(queryTaskManager.getEndfinishDate(),null)){
              wrapper.le("finish_date",queryTaskManager.getEndfinishDate());
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(queryTaskManager.getIsReceived(),null)){
              wrapper.eq("isReceived",queryTaskManager.getIsReceived());
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(queryTaskManager.getIsStart(),null)){
              wrapper.isNotNull("start_date");
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(queryTaskManager.getIsEnd(),null)){
              wrapper.isNotNull("end_date");
          }
          if (AdscmBaseUtils.getInstance().isNotEmpty(queryTaskManager.getIsEveryDayTask(),null)){
              wrapper.eq("isEveryDayTask",queryTaskManager.getIsEveryDayTask());
          }
         wrapper.orderBy("create_date",false);
            Page<TaskManager> page=new Page<>(queryTaskManager.getCurrentPage(),queryTaskManager.getPageSize());
            page = super.selectPage(page, wrapper);
            List<TaskManager> taskManagers = page.getRecords();
        for (TaskManager taskManager : taskManagers) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getCreator(),null)){
                JyUser jyUser = jyUserMapper.selectById(taskManager.getCreator());
                taskManager.setCreatorName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getPerformer(),null)){
                JyUser jyUser = jyUserMapper.selectById(taskManager.getPerformer());
                taskManager.setPerformerName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getDept(),null)){
                JyDept jyDept = jyDeptMapper.selectById(taskManager.getDept());
                taskManager.setDeptName(jyDept.getDeptName());
            }
        }
        page.setTotal(super.selectCount(wrapper));
        return page;
    }

    @Override
    public boolean insertWeekTask(Token token) throws AdscmSystemException {
        Date formateDate = AdscmDateUtils.getFormateDate(new Date());
        Date monday = AdscmDateUtils.getMonday(new Date());
        Date sunDay = AdscmDateUtils.getSunDay(new Date());
        int week=0;
        try {
            week = AdscmDateUtils.getWeek(new Date());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //先查询一下
        Wrapper<TaskManager> wrapper =new EntityWrapper<>();
        wrapper.eq("performer",token.getUser().getId());
        wrapper.eq("creator",token.getUser().getId());
        wrapper.ge("create_date",monday);
        wrapper.le("create_date",sunDay);
        wrapper.eq("isEveryDayTask","2");
        wrapper.andNew();
        wrapper.eq("task_name","第"+week+"周总结");
        List<TaskManager> taskManagers = super.selectList(wrapper);
        if (taskManagers.size()>0){
            throw new AdscmSystemException("这周已经创建了周总结");
        }
        TaskManager taskManager =new TaskManager();
        taskManager.setTaskName("第"+week+"周总结");
        taskManager.setCreateDate(new Date());
        taskManager.setCreator(token.getUser().getId().toString());
        taskManager.setIsReceived("-1");
        taskManager.setTaskResult("-1");
        taskManager.setPerformer(token.getUser().getId().toString());
        taskManager.setDept(token.getUser().getDeptId().toString());
        taskManager.setFinishDate(formateDate);
        taskManager.setStartDate(new Date());
        taskManager.setStartCreateDate(new Date());
        taskManager.setTaskSelfEvaluation("-1");
        taskManager.setIsReviewTask("-1");
        taskManager.setTaskState(1);
        taskManager.setIsEveryDayTask("2");
        boolean insert = super.insert(taskManager);
        return insert;
    }

    @Override
    public boolean insertMonthTask(Token token) throws AdscmSystemException {
        Date formateDate = AdscmDateUtils.getFormateDate(new Date());
        Date firstDay = AdscmDateUtils.getFirstDayOfTheMonth(new Date());
        Date lastDay = AdscmDateUtils.getLastDayOfTheMonth(new Date());
        String mm = new SimpleDateFormat("MM").format(new Date());
        //先查询一下
        Wrapper<TaskManager> wrapper =new EntityWrapper<>();
        wrapper.eq("performer",token.getUser().getId());
        wrapper.eq("creator",token.getUser().getId());
        wrapper.ge("create_date",firstDay);
        wrapper.le("create_date",lastDay);
        wrapper.eq("isEveryDayTask","3");
        List<TaskManager> taskManagers = super.selectList(wrapper);
        if (taskManagers.size()>0){
            throw new AdscmSystemException("这月已经创建了月总结");
        }
        TaskManager taskManager =new TaskManager();
        taskManager.setTaskName(mm+"月总结");
        taskManager.setCreateDate(new Date());
        taskManager.setCreator(token.getUser().getId().toString());
        taskManager.setIsReceived("-1");
        taskManager.setTaskResult("-1");
        taskManager.setPerformer(token.getUser().getId().toString());
        taskManager.setDept(token.getUser().getDeptId().toString());
        taskManager.setFinishDate(formateDate);
        taskManager.setStartDate(new Date());
        taskManager.setStartCreateDate(new Date());
        taskManager.setTaskSelfEvaluation("-1");
        taskManager.setIsReviewTask("-1");
        taskManager.setTaskState(1);
        taskManager.setIsEveryDayTask("3");
        boolean insert = super.insert(taskManager);
        return insert;
    }

    @Override
    public Boolean updateByCreator(Integer id) {
        TaskManager taskManager = super.selectById(id);
        taskManager.setIsCreatorUpdate("1");
        boolean b = super.updateById(taskManager);
        return b;
    }

    @Override
    public Boolean updateByPerformer(Integer id) {
        TaskManager taskManager = super.selectById(id);
        taskManager.setIsPerformerUpdate("1");
        boolean b = super.updateById(taskManager);
        return b;
    }

    @Override
    public boolean creatorSelected(Integer id, Token token) {
        boolean b=false;
        TaskManager taskManager = super.selectById(id);
        if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager,null)){
            if (taskManager.getCreator().equals(String.valueOf(token.getUser().getId()))){
                taskManager.setIsPerformerUpdate("0");
                b = super.updateById(taskManager);
            }
        }
        return b;
    }

    @Override
    public boolean performerSelected(Integer id, Token token) {
        boolean b=false;
        TaskManager taskManager = super.selectById(id);
        if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager,null)){
            if (taskManager.getPerformer().equals(String.valueOf(token.getUser().getId()))){
                taskManager.setIsCreatorUpdate("0");
                b = super.updateById(taskManager);
            }
        }
        return b;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteDBTaskManager(Integer id, Token token) throws AdscmSystemException {
       Boolean result=false;
        TaskManager taskManager = super.selectById(id);
        if (!"0".equals(taskManager.getIsEveryDayTask())){
            throw new AdscmSystemException("每日任务不能删除");
        }
        if (taskManager.getCreator().equals(taskManager.getPerformer())){
            result=  super.deleteById(id);
        }else {
            if (AdscmBaseUtils.getInstance().isNotEmpty(taskManager.getEndDate(),null)){
                taskManager.setTaskState(1);
                result=  super.updateById(taskManager);
            }else {
                throw new AdscmSystemException("该任务未结束");
            }
        }

        return  result;
    }


}
